namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Configuration;
    using SimpleWebServices.Globalization;
    using SimpleWebServices.Web.Routing;

    [InternalServerError]
    [Allow(Methods = "GET, HEAD, OPTIONS")]
    [CacheControl, ContentLanguage, ContentLocation, ContentMD5]
    public sealed class TenantRootController : Controller, IRegisterRoutes
    {
        void IRegisterRoutes.Register(RouteCollection routes)
        {
            if (null == routes)
            {
                throw new ArgumentNullException("routes");
            }

            routes.MapRoute(
                "GET /{tenant}",
                "{tenant}",
                new { controller = "TenantRoot", action = "SeeOther" },
                new { method = new HttpMethodConstraint("GET") });

            routes.MapRoute(
                "HEAD /{tenant}",
                "{tenant}",
                new { controller = "TenantRoot", action = "SeeOther" },
                new { method = new HttpMethodConstraint("HEAD") });
        }

        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "ASP.NET MVC requires the method to be an instance member.")]
        public ActionResult SeeOther()
        {
            new CultureInfo("en").SetCurrentCulture();

            string path = HttpContextFactory.Current.Request.TenantPath();

            return new SeeOtherResult(string.Concat(path, "/", RootConfiguration.Settings().Redirect ?? "home"));
        }
    }
}